import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:reader_app/test_page/painter_circle.dart';
//import 'package:tts_plugin/tts.dart';

///音频播放器
class AudioPlayerWidget extends StatefulWidget {
  final GestureTapCallback closeOnTap;
  final ValueChanged<bool> playStateChanged;
  final String ttsText;
  final String audioUrl;
  final bool showTitle;

  ///是否tts读报播放器，否则默认是 音频播放器
  final bool isTTSPlayer;

  const AudioPlayerWidget(
      {Key key,
      this.closeOnTap,
      this.audioUrl,
      this.isTTSPlayer = false,
      this.ttsText,
      this.showTitle = true,
      this.playStateChanged})
      : super(key: key);

  @override
  _AudioPlayerWidgetState createState() => _AudioPlayerWidgetState();
}

class _AudioPlayerWidgetState extends State<AudioPlayerWidget> {
  bool _isPlaying = false;
  AudioPlayer _audioPlayer;
  bool _hasStart = false;
  double currentDuration = 0;

  @override
  void initState() {
    super.initState();
    initPlayer();
  }

  @override
  void dispose() {
    super.dispose();
    _audioPlayer?.dispose();
    if (widget.isTTSPlayer) {
//      TtsPlugin.ttsStop();
    }
  }

  @override
  Widget build(BuildContext context) {
    var car = new Card(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.all(Radius.circular(22)),
      ),
      clipBehavior: Clip.antiAlias,
      elevation: 4,
      child: Container(
        height: 44,
        padding: EdgeInsets.only(left: 15, right: 17),
        width: widget.showTitle ? MediaQuery.of(context).size.width - 38 : 155,
        color: Colors.white,
        child: new Row(
          children: <Widget>[
            new Text(
              "$currentDuration".substring(0, 1),
              style: new TextStyle(fontSize: 1, color: Colors.transparent),
            ),
            new CustomPaint(
                foregroundPainter: new CirclePainter(
                  lineColor: widget.isTTSPlayer ? Colors.transparent : Colors.grey,
                  completeColor: Colors.red,
                  completePercent: currentDuration,
                  width: 2,
                ),
                child: new Image.asset(
                  "assets/images/audio_icon.png",
                  width: 27,
                  height: 27,
                )),
            widget.showTitle
                ? Expanded(
                    child: Padding(
                      padding: EdgeInsets.only(left: 12, right: 12),
                      child: new Text(
                        "大事大科技大厦就离开打算把合力科技奥德赛呢与我热代码三大数据的好使大事大科技大厦就离开打算把合力科技奥德赛呢与我热代",
                        style: new TextStyle(color: Colors.black87, fontSize: 14),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  )
                : new Padding(
                    padding: EdgeInsets.only(left: 12.5, right: 12.5),
                    child: new Container(
                      width: 0.5,
                      height: 20,
                      color: Colors.grey,
                    ),
                  ),
            new GestureDetector(
              child: new Image.asset(
                _isPlaying ? "assets/images/audio_pause.png" : "assets/images/audio_play.png",
                width: 20,
                height: 20,
              ),
              onTap: () {
                _pauseOrResume();
              },
            ),
            new Padding(
              padding: EdgeInsets.only(left: 12.5, right: 12.5),
              child: new Container(
                width: 0.5,
                height: 20,
                color: Colors.grey,
              ),
            ),
            new GestureDetector(
              onTap: () {
                _closePlayer();
              },
              child: new Image.asset(
                "assets/images/audio_close.png",
                width: 13.5,
                height: 13.5,
              ),
            )
          ],
        ),
      ),
    );
    return car;
  }

  ///初始化播放器
  initPlayer() {
    if (widget.isTTSPlayer) {
//      TtsPlugin.addTtsCompleteListener(() {
//        if (null != widget.playStateChanged) widget.playStateChanged(false);
//        setState(() {
//          _isPlaying = false;
//          _hasStart = false;
//        });
//      });
//      TtsPlugin.ttsPlay(widget.ttsText ?? "").then((value) {
//        setState(() {
//          _hasStart = true;
//          _isPlaying = true;
//          if (null != widget.playStateChanged) widget.playStateChanged(true);
//        });
//      });
//      return;
    }
    int _duration;
    int _currentDuration;
    _audioPlayer = new AudioPlayer();
    AudioPlayer.logEnabled = true;
    _audioPlayer?.play(widget.audioUrl, stayAwake: true);

    _audioPlayer?.onDurationChanged?.listen((Duration d) {
      if (null == _duration)
        setState(() {
          _duration = d.inSeconds;
        });
    });
    _audioPlayer?.onAudioPositionChanged?.listen((Duration d) {
      if (_currentDuration != d.inSeconds)
        setState(() {
          _currentDuration = d.inSeconds;
          currentDuration = (_currentDuration == null || _duration == null || _currentDuration == 0 || _duration == 0)
              ? 0
              : _currentDuration / _duration * 100;
//          debugPrint('监听到当前播放了  $_currentDuration');
          if (!_hasStart) {
            _hasStart = true;
            if (null != widget.playStateChanged) widget.playStateChanged(true);
            _isPlaying = (null != _currentDuration && null != _duration) && (_currentDuration < _duration);
          }
        });
    });
    _audioPlayer?.onPlayerCompletion?.listen((data) {
      if (null != widget.playStateChanged) widget.playStateChanged(false);
      setState(() {
        _isPlaying = false;
        _hasStart = false;
      });
    });
  }

  ///暂停或者继续播放
  void _pauseOrResume() {
    if (!_hasStart) {
      return;
    }
    if (_isPlaying) {
      if (widget.isTTSPlayer) {
//        TtsPlugin.ttsPause();
      } else {
        _audioPlayer?.pause();
      }
      if (null != widget.playStateChanged) widget.playStateChanged(false);
      setState(() {
        _isPlaying = false;
      });
    } else {
      if (widget.isTTSPlayer) {
//        TtsPlugin.ttsResume();
      } else {
        _audioPlayer?.resume();
      }
      if (null != widget.playStateChanged) widget.playStateChanged(true);
      setState(() {
        _isPlaying = true;
      });
    }
  }

  ///关闭播放器
  void _closePlayer() {
    if (null != widget.closeOnTap) {
      // todo 这里可以优化，完善
      _audioPlayer?.stop();
      _audioPlayer?.dispose();
      if (widget.isTTSPlayer) {
//        TtsPlugin.ttsStop();
      }
      widget.closeOnTap();
    }
  }
}
